<?php

namespace StudyBuddy;

/**
 *
 * Class for rendering <div> with user profile
 * This class is used for generating div on page
 * /user/$id/
 *
 */
class ProfileDiv extends StudyBuddyObject {

    /**
     * Flag indicates that oauth extension
     * is available
     *
     * @var bool
     */
    protected $hasOauth = false;

    /**
     *
     * User whose profile page being created
     * @var object of type User
     */
    protected $oUser;

    /**
     * Constructor
     * 
     * @param Registry $oRegistry
     */
    public function __construct(Registry $oRegistry) {
        $this->oRegistry = $oRegistry;
        $this->hasOauth = \extension_loaded('oauth');
    }

    /**
     * Setter for $this->oUser
     * 
     * @param User $oUser
     */
    public function setUser(User $oUser) {
        $this->oUser = $oUser;

        return $this;
    }

    public function getHtml() {
        $edit = '';
        $lastActive = $this->oUser['i_lm_ts'];
        $lastActive = (!empty($lastActive)) ? $lastActive : $this->oUser['i_reg_ts'];
        $rep = $this->oUser->getReputation();

        d('rep: ' . $rep);
        $uid = $this->oUser->getUid();
        $isSameUser = ($this->oRegistry->Viewer->getUid() === $uid);
        $desc = \trim($this->oUser['description']);
        $desc = (empty($desc)) ? '' : Utf8String::factory($desc, 'utf-8', true)->linkify()->valueOf();

        $vars = array(
            'editLink' => $edit,
            'username' => $this->oUser->username,
            'avatar' => $this->oUser->getAvatarImgSrc(),
            'reputation' => $rep,
            'name' => $this->oUser->getDisplayName(),
            'genderLabel' => 'Gender',
            'gender' => $this->getGender(),
            'since' => date('F j, Y', $this->oUser->i_reg_ts),
            'lastActivity' => TimeAgo::format(new \DateTime(date('r', $lastActive))),
            'website' => $this->oUser->getUrl(),
            'twitter' => '<div id="my_tw">' . $this->getTwitterAccount($isSameUser) . '</div>',
            'age' => $this->oUser->getAge(),
            'facebook' => '<div id="my_fb">' . $this->getFacebookAccount($isSameUser) . '</div>',
            'tumblr' => '<div id="my_tm">' . $this->getTumblrAccount($isSameUser) . '</div>',
            'blogger' => '<div id="my_bg">' . $this->getBloggerAccount($isSameUser) . '</div>',
            'linkedin' => '<div id="my_li">' . $this->getLinkedInAccount($isSameUser) . '</div>',
            'location' => $this->oUser->getLocation(),
            'description' => \wordwrap($desc, 50), // @todo this is not unicode-safe! Must update it!
            'editRole' => Usertools::getHtml($this->oRegistry, $this->oUser),
            'followButton' => $this->makeFollowButton(),
            'followers' => ShowFollowers::factory($this->oRegistry)->getUserFollowers($this->oUser),
            'following' => ShowFollowers::factory($this->oRegistry)->getUserFollowing($this->oUser),
			'hasbadges' => $this->hasBadges(),
            'confirmation' => $this->makeConfirmBlock(),
        );

        if ($isSameUser || $this->oRegistry->Viewer->isAdmin()) {
            $vars['divSetting'] = $this->makeSettingDiv();
        }
        return \tplUserInfo::parse($vars);
    }
	
	function hasBadges(){
		
		$cur = $this->oRegistry->Mongo->USER_BADGES->find(array('i_uid' => $this->oUser->getUid()));
		$i = 0;
		$arrcheck = array();
		$html = '';
		foreach($cur as $obj){
			if(!in_array($obj['i_bid'], $arrcheck)) {
				$html = $html . '<a class="badge" href="/badges/'.$obj['i_bid'].'">
									<span class="'.$obj['badges_type'].'">&#9679;</span>&nbsp;'.$obj['badges'].'</a>';
				$i++;					
			}
			$arrcheck[] = $obj['i_bid'];
		}
		$html1 = '<h4 style="padding-left:10px;">' . $i . ' Badges</h4><div class="badges"><div><div class="badgesdiv"><ul>';
		
		$html = $html1 . $html . '</ul></div></div></div>';
		
		return $html;
	
	}

    /**
     * Get either the link to @username of Twitter account if user has one
     * OR html for the button to connect Twitter account
     * to Existing Account
     *
     *
     * @param object $oRegistry
     * @param object $oUser
     *
     * @return string html html of Connect button
     * or just plain text string with @username
     *
     */
    public function getTwitterAccount($isSameUser) {

        $t = $this->oUser->getTwitterUrl();
        if (!empty($t)) {
            return $t;
        }

        if ($this->hasOauth && $isSameUser) {
            $aTwitter = $this->oRegistry->Ini->getSection('TWITTER');
            if (!empty($aTwitter['TWITTER_OAUTH_KEY']) && !empty($aTwitter['TWITTER_OAUTH_SECRET'])) {
                return '<div id="connect_twtr" class="twsignin ajax ttt btn_connect rounded4" title="Connect Twitter Account"><img src="/images/tw-user.png" width="16" height="16"><span class="_bg_tw">Connect Twitter</span></div>';
            }
        }

        return '';
    }

    /**
     * Get either the link to Tumblr blog
     * if user has one
     * OR html for the button to connect Tumblr account
     * to Existing Account
     *
     *
     * @param object $oRegistry
     * @param object $oUser
     *
     * @return string html of Connect button
     * or link to user's Tumblr blog
     *
     */
    public function getTumblrAccount($isSameUser) {

        $t = $this->oUser->getTumblrBlogLink();
        d('tumblr blog url: ' . $t);
        if (!empty($t)) {
            return $t;
        }

        if ($this->hasOauth && $isSameUser) {
            $a = $this->oRegistry->Ini->getSection('TUMBLR');
            if (!empty($a) && !empty($a['OAUTH_KEY']) && !empty($a['OAUTH_SECRET'])) {
                return '<div id="connect_tumblr" class="add_tumblr ajax ttt btn_connect rounded4" title="Connect Tumblr Blog"><img src="/images/tumblr_16.png" width="16" height="16"><span class="_bg_tw">Connect Tumblr Blog</span></div>';
            }
        }

        return '';
    }

    /**
     * Get either the link to Tumblr blog
     * if user has one
     * OR html for the button to connect Tumblr account
     * to Existing Account
     *
     *
     * @param object $oRegistry
     * @param object $oUser
     *
     * @return string html of Connect button
     * or link to user's Tumblr blog
     *
     */
    public function getBloggerAccount($isSameUser) {

        $t = $this->oUser->getBloggerBlogLink();
        d('blojgger blog url: ' . $t);
        if (!empty($t)) {
            return $t;
        }

        if ($this->hasOauth && $isSameUser) {
            $a = $this->oRegistry->Ini->getSection('BLOGGER');
            if (!empty($a) && !empty($a['OAUTH_KEY']) && !empty($a['OAUTH_SECRET'])) {
                return '<div id="connect_blogger" class="add_blogger ajax ttt btn_connect rounded4" title="Connect Blogger.com Blog"><img src="/images/blogger_16.png" width="16" height="16"><span class="_bg_tw">Connect Blogger Blog</span></div>';
            }
        }

        return '';
    }

    /**
     * Get either the link to Tumblr blog
     * if user has one
     * OR html for the button to connect Tumblr account
     * to Existing Account
     *
     *
     * @param object $oRegistry
     * @param object $oUser
     *
     * @return string html of Connect button
     * or link to user's Tumblr blog
     *
     */
    public function getLinkedInAccount($isSameUser) {

        $t = $this->oUser->getLinkedinLink();
        d('linkedIn url: ' . $t);
        if (!empty($t)) {
            return $t;
        }

        if ($this->hasOauth && $isSameUser) {
            $a = $this->oRegistry->Ini->getSection('LINKEDIN');
            if (!empty($a) && !empty($a['OAUTH_KEY']) && !empty($a['OAUTH_SECRET'])) {
                return '<div id="connect_linkedin" class="add_linkedin ajax ttt btn_connect rounded4" title="Connect LinkedIn Account"><img src="/images/linkedin_16.png" width="16" height="16"><span class="_bg_tw">Connect LinkedIn</span></div>';
            }
        }

        return '';
    }

    /**
     * Get either the link to Facebook profile
     * if user has one
     * OR html for the button to connect Facebook account
     * to Existing Account
     *
     *
     * @param object $oRegistry
     * @param object $oUser
     *
     * @return string html of Connect button
     * or link to Facebook profile page
     *
     */
    public function getFacebookAccount($isSameUser) {

        $f = $this->oUser->getFacebookUrl();
        if (!empty($f)) {
            return $f;
        }

        if ($this->hasOauth && $isSameUser) {
            $aFB = $this->oRegistry->Ini->getSection('FACEBOOK');
            if (!empty($aFB) && !empty($aFB['APP_ID'])) {

                return '<div id="connect_fb" class="fbsignup ajax ttt btn_connect rounded4" title="Connect Facebook Account"><img src="/images/facebook_16.png" width="16" height="16"><span class="_bg_tw">Connect Facebook</span></div>';
            }
        }

        return '';
    }

    /**
     * Get textual value of "Gender" M/F
     *
     * @todo translate string Male/Female
     * @param string $gender
     * @return string
     */
    protected function getGender() {
        $gender = $this->oUser['gender'];
        switch ($gender) {
            case 'M':
                $ret = 'Male';
                break;

            case 'F':
                $ret = 'Female';
                break;

            default:
                $ret = '';
        }

        return $ret;
    }

    /**
     * Make a follow user button
     * checks that user is not the same
     * as viewer, otherwise just returns
     * empty string
     *
     *
     * @param Registry $oRegistry
     * @param User $oUser use who to follow
     * @return string html of "Follow" button
     * of empty string if Viewer is same as User
     *
     */
    public function makeFollowButton() {

        $button = '';
        $oViewer = $this->oRegistry->Viewer;
        $uid = $this->oUser->getUid();

        if ($uid !== $oViewer->getUid()) {

            $aVars = array(
                'id' => $uid,
                'icon' => 'cplus',
                'label' => 'Follow',
                'class' => 'follow',
                'type' => 'u',
                'title' => 'Follow this user'
            );

            if (in_array($uid, $oViewer['a_f_u'])) {
                $aVars['label'] = 'Following';
                $aVars['class'] = 'following';
                $aVars['icon'] = 'check';
                $aVars['title'] = 'You are following this user';
            }

            $button = '<div class="fl mt10 mb10"><div class="follow_wrap">' . \tplFollowButton::parse($aVars, false) . '</div></div>';
        }

        return $button;
    }
    
    protected function makeClearCache() {
        $html = '';
        if ($this->oRegistry->Viewer->isAdmin()) {
            $html = '<div class="tool"> 
			<div class="icn sweep">&nbsp;</div> 
			<div class="tool_link"><a href="/clearcache/" class="ajax clearcache">Clear Cache</a></div> 
		</div>';
        }
        return $html;
    }

    protected function makeListFlag() {
        $html = '';
        if ($this->oRegistry->Viewer->isAdmin()) {
            $html = '<div class="tool"> 
                        <div class="icn flag">&nbsp;</div> 
                        <div class="tool_link"><a href="/listflag/" class="ajax listflag">List Flags</a></div> 
                    </div>';
        }
        return $html;
    }
	
    protected function makeSettingDiv(){
	
		$role = $this->oRegistry->Viewer->getRoleId();
	
		if(strstr($role, 'tutor')) {
			$link = '<a href="/regtutor">Edit Profile</a>';

		}else{
			$link = '<a href="/editprofile/'.$this->oUser->getUid().'">Edit Profile</a>';
		}
		
        return '<div style="position:absolute; top:0; right:0;">
                    <div id="tools" style="width:150px"> 
                        '.$this->makeConfirmBlock().'
                        <div class="tool">
                            <div class="icn profile">&nbsp;</div> 
                            <div class="tool_link">'. $link .'
							</div> 
                        </div>
                        <div class="tool"> 
                            <div class="icn emailprefs">&nbsp;</div> 
                            <div class="tool_link"><a href="/emailoptions/">Email Preferences</a></div> 
                        </div>  
                        <div class="tool"> 
                            <div class="icn changepass">&nbsp;</div> 
                            <div class="tool_link"><a href="/changepwd/">Change Password</a></div> 
                        </div> 
                        '.$this->makeClearCache().'
                        '.$this->makeListFlag().'
                    </div>
                </div>';
    }

    protected function makeConfirmBlock() {
        $role = $this->oRegistry->Viewer->getRoleId();
        $email = $this->oRegistry->Viewer->email;
        if (strstr($role, 'unactivated')) {
            return \tplConfirmemail::parse(array('email' => $email));
        }

        return '';
    }

}
